const { db } = require("./database");
const { isEmpty } = require("lodash");

/**
 * 查询
 *
 * @param {request} req 请求对象
 * @param {string} table 表名
 * @param {Array} wheres 字符数组
 * @param {Array} params 参数列表
 * @param {Array} orderBy 排序
 * @returns query 对象
 */
const query = async (req, table, options = {}) => {
  const { fields = "*", wheres = [], params = [], orderBy = [] } = options;
  const { limit = 10, offset = 0 } = req.query;
  // where 子句
  const where = isEmpty(wheres) ? "" : `where ${wheres.join(" and ")}`;
  // order by 子句
  const order = isEmpty(orderBy) ? "" : `order by ${orderBy.join(", ")}`;
  // 获取查询的总数
  let sql = `select count(*) as count from ${table} ${where}`;
  const { count } = await db.findOne(sql, params);
  // 执行查询 sql
  sql = `select ${fields} from ${table} ${where} ${order} limit ${offset}, ${limit}`;
  const results = await db.select(sql, params);
  return {
    count,
    limit,
    offset,
    page: offset / limit + 1,
    results,
  };
};

const findOne = async (id, table, options = {}) => {
  const { fields = "*", wheres = ["id = ?"], params = [id] } = options;
  const object = await db.findOne(
    `select ${fields} from ${table} where ${wheres.join(" and ")}`,
    params
  );
  return {
    success: !!object,
    object,
  };
};

module.exports = {
  query,
  findOne,
};
